<template>
  <div class="mui-pages" style="background-color: #fff;">
    <header class="mui-bar mui-bar-nav">
      <div class="header-common-title flex-justify-start">
        <a @click="fn.back()" href="javascript:void(0)"><img class="back-btn" src="../../../../static/images/back.png"></a>
        <div class="header-search flex-center">添加组织生活</div>
        <a @click="save(0)" href="javascript:void(0)" class="header-right-btn flex-center">提交</a>
      </div>
    </header>
    <div id="slider" class="mui-slider mui-fullscreen">
      <div class="mui-scroll-wrapper mui-slider-indicator mui-segmented-control mui-segmented-control-inverted">
        <div class="meeting-tab flex-justify-start">
          <a @click="tabIndex=0" :class="{'mui-active':tabIndex==0}" class="mui-control-item" href="javascript:void(0)">会议基本信息</a>
          <p style="width: 15px"></p>
          <a @click="tabIndex=1" :class="{'mui-active':tabIndex==1}" class="mui-control-item" href="javascript:void(0)">附件</a>
        </div>
      </div>
      <div class="mui-slider-group">
        <!-- ---------会议基本信息---------start -->
        <div v-show="tabIndex==0" id="meetingInfo" class="mui-slider-item mui-control-content mui-active">
          <div id="scroll1" class="mui-scroll-wrapper">
            <div class="mui-scroll record-member-lists">
              <ul class="mui-table-view meeting-editor-lists">
                <li class="mui-table-view-cell flex-between-center" style="display: none">
                  <b><span class="mine-lists-money">·</span>标题：</b>
                  <span class="mine-lists-content">
											<input class="setup-input" type="text" v-model="data.title" placeholder="请输入标题" /></span>
                </li>
                <li class="mui-table-view-cell flex-between-center" id="typeSelect" @click="go('scheduleTypes')">
                  <b><span class="mine-lists-money">·</span>类型：</b>
                  <span class="mine-lists-content">
											<input class="setup-input" type="text" readonly v-model="data.typeLabel" placeholder="请选择会议类型" /></span>
                </li>
                <li class="mui-table-view-cell flex-between-center" @click="showActive()">
                  <b><span class="mine-lists-money">·</span>范围：</b>
                  <span class="mine-lists-content">
											<input class="setup-input" type="text" readonly v-model="data.scopeLabel " placeholder="请选择会议范围" /></span>
                </li>
                <li class="mui-table-view-cell flex-between-center">
                  <b><span class="mine-lists-money">·</span>主题：</b>
                  <span class="mine-lists-content">
											<input  class="setup-input" type="text" v-model="data.subject" placeholder="请输入会议主题" />
                  </span>
                </li>
                <li class="mui-table-view-cell flex-between-center">
                  <b><span class="mine-lists-money">·</span>创建人：</b>
                  <span class="mine-lists-content">{{userInfo.fullname}}</span>
                </li>
                <li @click="selectPeople('attendUserName')" class="mui-table-view-cell flex-between-center" id="joinPeople">
                  <b><span class="mine-lists-money">·</span>参与人员：</b>
                  <span class="mine-lists-content">
											<input class="setup-input" type="text" readonly v-model="data.attendUserName " placeholder="请选择参与人员" /></span>
                </li>
                <li @click="showTimePicker()" class="mui-table-view-cell flex-between-center">
                  <b><span class="mine-lists-money">·</span>会议时间：</b>
                  <span class="mine-lists-content" id="meetingTime">
											<input class="setup-input" type="text" readonly v-model="data.meetTime " placeholder="请选择会议时间" /></span>
                </li>
                <li class="mui-table-view-cell flex-between-center" @click="selectAddress()" v-if="!isOutSide()">
                  <b><span class="mine-lists-money">·</span>会议地点：</b>
                  <span class="mine-lists-content">
											<input class="setup-input" type="text" readonly v-model="data.address" placeholder="请选择会议地点" /></span>
                </li>
                <li class="mui-table-view-cell flex-between-center" v-if="data.address==addressWriteName || isOutSide()">
                  <b><span class="mine-lists-money">·</span>会议地点：</b>
                  <span class="mine-lists-content">
											<input class="setup-input" type="text" v-model="data.addressWrite" placeholder="请填写会议地点" /></span>
                </li>
                <li v-if="!isOutSide()" @click="selectPeople('compereUserName')" class="mui-table-view-cell flex-between-center">
                  <b><span class="mine-lists-money">·</span>主持人：</b>
                  <span class="mine-lists-content">
											<input class="setup-input" type="text" readonly v-model="data.compereUserName " placeholder="请输入主持人" /></span>
                </li>
                <li v-if="!isOutSide()" @click="selectPeople('recordEUserName')" class="mui-table-view-cell flex-between-center">
                  <b><span class="mine-lists-money">·</span>记录人：</b>
                  <span class="mine-lists-content">
											<input class="setup-input" type="text" readonly v-model="data.recordEUserName " placeholder="请输入记录人" /></span>
                </li>
              </ul>
            </div>
          </div>
        </div>
        <!-- ---------会议基本信息---------end -->
        <!-- ---------附件-----------start -->
        <div v-show="tabIndex==1" id="enclosure" class="mui-slider-item mui-control-content">
          <div class="mui-scroll-wrapper">
            <div class="mui-scroll record-member-lists">
              <p class="record-item-title">会议附件：</p>
              <ul class="mui-content-padded flex-justify-start">
                <cube-upload ref="upload"
                   action=""
                   v-model="files"
                   accept="*/*"
                   :simultaneous-uploads="1"
                   @files-added="uploadFile"
                   @file-removed="fileRemoved"
                   @input="onInput"
                />
              </ul>
            </div>
          </div>
        </div>
        <!-- ---------附件---------end -->
      </div>
      <div v-if="false" @click="save(1)" class="storage-btn">暂存</div>
    </div>

  </div>
</template>

<script>
  import tools from '@/utils/tools'
  import loginService from '@/service/loginService'
  import moment from 'moment'
  import fileIcon from '../../../../static/images/up_document.png'
  export default {
    components: {
    },
    data () {
      return {
        fn: tools,
        data: {
          title: '',
          address: '',
          attendUserId: '',
          attendUserName: '',
          compereUserId: '',
          compereUserName: '',
          dealFlag: '',
          meetTime: '',
          noticeFile: '',
          partyGroupId: '',
          partyGroupName: '',
          partySmallGroupId: '',
          partySmallGroupName: '',
          recordEUserId: '',
          recordEUserName: '',
          scope: '',
          scopeLabel: '',
          subject: '',
          type: '',
          typeLabel: ''
        },
        addressWriteName: '填写会议地址',
        tabIndex: 0,
        options: {
          pullUpLoad: true,
          scrollbar: false
        },
        userInfo: this.$store.state.userInfo,
        swipeData: [],
        attachmentList: [],
        infinite: true,
        pageIndex: 0,
        files: [],
        hydd: []
      }
    },
    created () {
      this.resumeData()
      this.appGetMeetingAddress()
    },
    methods: {
      isCanEdit () {
        return !(this.$store.state.addScheduleStudy === true)
      },
      go (name) {
        this.storeData()
        if (!this.isCanEdit() && (['scheduleTypes'].indexOf(name) >= 0)) {
          return false
        }
        this.$router.push({name: name})
      },
      resumeData () {
        if (this.$store.state.scheduleAddData) {
          this.data = this.$store.state.scheduleAddData
        }
        if (this.$store.state.scheduleTypeSelected) {
          let arrNames = []
          let arrKeys = []
          this.$store.state.scheduleTypeSelected.forEach((v) => {
            arrKeys.push(v.value)
            arrNames.push(v.name)
          })
          this.data.typeLabel = arrNames.join(',')
          this.data.type = arrKeys.join(',')
        }
      },
      isOutSide () {
        let arr = this.$store.state.scheduleTypeSelected
        if (Array.isArray(arr) && arr.length > 0 && arr[0].name.indexOf('室外') > 0) {
          return true
        }
        return false
      },
      edit (data) {
        this.$router.push({name: 'scheduleDetail'})
      },
      save (flag) {
        if (this.data.typeLabel === '') {
          return tools.tip('请选择会议类型')
        }
        if (this.data.scopeLabel === '') {
          return tools.tip('请选择会议范围')
        }
        if (this.data.subject === '') {
          return tools.tip('会议主题不能为空')
        }
        if (this.data.attendUserName === '') {
          return tools.tip('请选择参与人员')
        }
        if (this.data.meetTime === '') {
          return tools.tip('请选择会议时间')
        }
        if (this.data.address === '' && !this.isOutSide()) {
          return tools.tip('请选择会议地点')
        }
        if (!this.isOutSide() && this.data.compereUserName === '') {
          return tools.tip('请选择主持人')
        }
        if (!this.isOutSide() && this.data.recordEUserName === '') {
          return tools.tip('请选择记录人')
        }
        let data = _.extend({}, this.data)
        let userInfo = this.$store.state.userInfo
        let strFiles = this.makeStr(this.attachmentList)
        if (this.isOutSide()) {
          data.address = data.addressWrite
          data.ztdrAddress = data.addressWrite
        }
        if (data.address === this.addressWriteName) {
        }
        if (flag === 1) {
          data.isTemporary = '1'
        }
        data.noticeFile = strFiles
        data.partyGroupId = userInfo.partyMemberModel.partyGroupId
        data.partyGroupName = userInfo.partyMemberModel.partyGroupName
        data.partySmallGroupId = userInfo.partyMemberModel.partySmallGroupId
        data.partySmallGroupNam = userInfo.partyMemberModel.partySmallGroupNam
        data.dealFlag = this.isOutSide() ? '1' : '0'
        loginService.saveAppInsPartyMeetingBean(data).then((res) => {
          if (res.message.indexOf('参数不完整时的异常') >= 0) {
            tools.tip('带*号的请填写内容')
          }
          if (res.code === 200) {
            if (flag === 1) {
              tools.tip('暂存成功')
            } else {
              // 添加成功要关联周度学习详情
              tools.tip('添加成功')
              if (this.relativeStudy(res.data.id)) {
                return false
              }
            }
            this.clearStore()
            tools.back()
          }
        })
      },
      // 添加成功要关联周度学习详情
      relativeStudy (id) {
        if(this.$store.state.addScheduleStudy === true) {
          let data = {
            weekPlanId: this.$store.state.weekId,
            meetingId: id
          }
          loginService.setRelationMeetingToWeekPlan(data).then(res => {
            if (res.code !== 200) {
              return tools.tip('关联失败，请返回学习详情界面添加关联')
            }
            this.clearStore()
            return tools.back()
          })
          return true
        }
      },
      clearStore () {
        delete this.$store.state.scheduleAddData
        delete this.$store.state.scheduleTypeSelected
        delete this.$store.state.schedulePeopleListSelectedattendUserName
        delete this.$store.state.schedulePeopleListSelectedcompereUserName
        delete this.$store.state.schedulePeopleListSelectedrecordEUserName
        delete this.$store.state.addScheduleStudy
      },
      detail (data) {
        this.$store.state.scheduleData = data
        this.$router.push({name: 'scheduleDetail'})
      },
      openSignList (signSatus) {
        this.$router.push({'path': `/scheduleSignPeople/${signSatus}`})
      },
      // 开始签到
      startSign (meetingId) {
        loginService.startPartyMemberSign(meetingId).then((res) => {
          this.$router.push({'path': `/scheduleSign/${meetingId}`})
          if (res.code === 200) {
          }
        })
      },
      storeData () {
        this.$store.state.scheduleAddData = this.data
      },
      // 选择人员
      selectPeople (modelName) {
        if (this.data.scope === '') {
          return tools.tip('请先选择范围')
        }
        this.storeData()
        this.$router.push({path: `/schedulePeople/${modelName}`})
      },
//      会议时间格式：2019-12-06 21:48:00 精确到分
      showTimePicker () {
        this.$createTimePicker({
          minuteStep: 1,
          delay: 1,
          min: parseInt(moment().subtract(10, 'days').format('x')),
          day: {
            len: 90,
            filter: ['今天', '明天'],
            format: 'M月d日'
          },
          onSelect: (selectedTime, selectedText, formatedTime) => {
            this.data.meetTime = moment(selectedTime).format('YYYY-MM-DD HH:mm:ss')
            this.$forceUpdate()
          }
        }).show().setTime(parseInt(moment().format('x')))
      },
      // 选择会议范围
      showActive () {
        this.$createActionSheet({
          title: '会议范围',
          active: 10,
          data: [
            {
              scope: 'dzb',
              content: '支部'
            },
            {
              scope: 'dxz',
              content: '党小组'
            }
          ],
          onSelect: (item, index) => {
            this.data.scopeLabel = item.content
            this.data.scope = item.scope
            this.$forceUpdate()
          },
          onCancel: () => {
          }
        }).show()
      },
      // 选择会议地点
      selectAddress () {
        this.$createActionSheet({
          title: '会议地点',
          active: 10,
          data: this.hydd,
          onSelect: (item, index) => {
            this.data.address = item.content
            this.$forceUpdate()
          },
          onCancel: () => {
          }
        }).show()
      },
      makeStr (arr) {
        return JSON.stringify(arr)
        let arrImg = []
        arr.forEach((v) => {
          arrImg.push(`{'fileId':'${v.fileId}','fileName':'${v.fileName}','totalBytes':${v.totalBytes}}`)
        })
        return `[${arrImg.join(',')}]`
      },
      // 删除文件
      fileRemoved (file) {
        this.attachmentList.some((v, i) => {
          if (v.fileName === file.file.name && v.totalBytes === file.file.size) {
            this.attachmentList.splice(i, 1)
            return false
          }
        })
      },
      uploadFile (file) {
        let uploadFile = file[0]
        let formData = new FormData()
        formData.append('file', uploadFile)
        loginService.updFiles(formData).then((res) => {
          if (res.code !== 200) {
            return tools.tip(res.message)
          }
          this.attachmentList.push({'fileId': res.data[0].fileId, 'fileName': uploadFile.name, 'totalBytes': res.data[0].totalBytes})
        })
      },
      onInput (file) {
        this.$refs.upload.files.map((v) => {
          if (!tools.isImage(v.name)) {
            v.url = fileIcon
          }
          return v
        })
      },
      // 会议地点
      appGetMeetingAddress () {
        this.hydd = []
        loginService.appGetMeetingType('HYDD').then((res) => {
          if (res.code === 200) {
            res.data.map((v, i) => {
              let data = {
                content: v.name
              }
              this.hydd.push(data)
            })
            let data = {
              content: this.addressWriteName
            }
            this.hydd.push(data)
          }
        })
      }
    }
  }
</script>
<style scoped="">
  .storage-btn {
    z-index:99;
  }
</style>
